package com.yaodian100.mall.member.web;

import java.io.File;
import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.entity.SimplePager;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.DomainService;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.ec.common.EcConstant;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.order.service.OrderService;
import com.yaodian100.ec.payment.entity.ApplyClaim;
import com.yaodian100.ec.payment.entity.BankTransfer;
import com.yaodian100.ec.payment.service.TransferService;
import com.yaodian100.mall.member.util.UserData;

//TODO 前台頁面套版
public class ApplyClaimAction extends ActionSupport implements Preparable {
	private static final long serialVersionUID = -1402701108549348394L;
	/** logger */
	private final Logger logger = LoggerFactory.getLogger(ApplyClaimAction.class);
	private Menu claimTypeMenu; // 與 getter, setter
	private Menu claimStatusMenu; // 與 getter, setter
	private Menu sourceRemitMenu;
	private SimplePager pager;
	private DomainService<Menu> menuService; // 與 setter
	private TransferService transferService;
	private TransferService transferServiceRemote;
	private OrderService orderService;
	private List<BankTransfer> bankTransferList;
	private int bankTransferSize;
	private ApplyClaim applyClaim;
	private BankTransfer bankTransfer;

	private boolean checkResult;
	private String bktId;

	/* 招领单页面参数 */
	private String orderId;
	private String claimName;
	private String bankName;
	private String claimAmount;
	private String expectDate;
	private String claimType;
	private String contactPhone;
	private String contactEmail;
	private File claimImg;
	private String claimId;
	private UserData userData;

	private String uploadFileName;// 设置上传文件的文件名
	private String uploadContentType;// 上传文件的类型

	/* tiles 參數 */
	private String pageDescription;
	private String pageTitle;
	private String pageKeywords;

	/**
	 * 填写招领单(新增)
	 * 
	 * @return
	 * @throws Exception
	 */
	public String add() throws Exception {
		loginInit();
		if (StringUtils.isBlank(bktId)) {
			addActionError("传入参数错误");
		}
		bankTransfer = transferService.getBankTransfer(bktId);
		if (null == bankTransfer) {
			addActionError("找不到汇款单资料");
			return search();
		}
		return "edit";
	}

	public String checkOrderId() throws CoreException {
		loginInit();
		Orders order = orderService.get(orderId);
		if (null != order && order.getMemberId().equals(userData.getMemberId())) {
			checkResult = true;
		} else {
			checkResult = false;
		}
		return "jsonCheckOrderId";
	}

	/**
	 * 资料验证
	 * 
	 * @return
	 * @throws Exception
	 */
	boolean cliamValidate() throws Exception {
		loginInit();
		/**************************** 必填栏位 ****************************/

		if (StringUtils.isBlank(orderId)) {
			addFieldError("orderIdMsg", "请输入订单编号");
		}

		Orders order = orderService.get(orderId);
		if (null == order || !userData.getMemberId().equals(order.getMemberId())) {
			addFieldError("orderIdMsg", "订单编号错误");
		}

		if (StringUtils.isBlank(claimName)) {
			addFieldError("claimNameMsg", "请输入汇款人");
		}

		if (StringUtils.isBlank(bankName)) {
			addFieldError("bankNameMsg", "请输入汇款行");
		}

		if (StringUtils.isBlank(claimAmount) || NumberUtils.createBigDecimal(claimAmount).intValue() == 0) {
			addFieldError("claimAmountMsg", "请输入汇款金额");
		}

		if (StringUtils.isBlank(expectDate)) {
			addFieldError("expectDateMsg", "请输入汇款日期");
		}

		if (StringUtils.isBlank(contactEmail)) {
			addFieldError("contactEmailMsg", "请输入邮箱地址");
		}

		if (StringUtils.isBlank(contactPhone)) {
			addFieldError("contactPhoneMsg", "请输入电话");
		}

		if (StringUtils.isBlank(uploadFileName)) {
			addFieldError("claimImgMsg", "请上传汇款凭证");
		}

		if (getFieldErrors().isEmpty()) {
			return true;
		} else {
			return false;
		}
	}

	public ApplyClaim getApplyClaim() {
		return applyClaim;
	}

	public String getBankName() {
		return bankName;
	}

	public BankTransfer getBankTransfer() {
		return bankTransfer;
	}

	public List<BankTransfer> getBankTransferList() {
		return bankTransferList;
	}

	public int getBankTransferSize() {
		return bankTransferSize;
	}

	public String getBktId() {
		return bktId;
	}

	public String getClaimAmount() {
		return claimAmount;
	}

	public String getClaimId() {
		return claimId;
	}

	public File getClaimImg() {
		return claimImg;
	}

	public String getClaimName() {
		return claimName;
	}

	public Menu getClaimStatusMenu() {
		return claimStatusMenu;
	}

	public String getClaimType() {
		return claimType;
	}

	public Menu getClaimTypeMenu() {
		return claimTypeMenu;
	}

	public String getContactEmail() {
		return contactEmail;
	}

	public String getContactPhone() {
		return contactPhone;
	}

	public String getExpectDate() {
		return expectDate;
	}

	public String getOrderId() {
		return orderId;
	}

	public String getPageDescription() {
		return pageDescription;
	}

	public String getPageKeywords() {
		return pageKeywords;
	}

	public SimplePager getPager() {
		return pager;
	}

	public String getPageTitle() {
		return pageTitle;
	}

	public Menu getSourceRemitMenu() {
		return sourceRemitMenu;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public UserData getUserData() {
		return userData;
	}

	public boolean isCheckResult() {
		return checkResult;
	}

	void loginInit() {
		if (null == userData) {
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
					ServletActionContext.HTTP_RESPONSE);
			userData = new UserData(request, response);
			logger.info("userdata");
		}
	}

	public void prepare() throws Exception {
		clearErrorsAndMessages();
		// if (null == pager)
		// pager = new SimplePager();

		if (null == claimTypeMenu) {
			claimTypeMenu = menuService.get("ApplyClaim.ClaimType");
		}

		if (null == claimStatusMenu) {
			claimStatusMenu = menuService.get("ApplyClaim.ClaimStatus");
		}

		if (null == sourceRemitMenu) {
			sourceRemitMenu = menuService.get("BankTransfer.SourceRemit");
		}
		if (null == applyClaim) {
			applyClaim = new ApplyClaim();
		}

		pageDescription = ServerValue.getSeoProp().getProperty("claim.description");
		pageKeywords = ServerValue.getSeoProp().getProperty("claim.keywords");
		pageTitle = ServerValue.getSeoProp().getProperty("claim.title");

		logger.info("prepare ok");
	}

	/**
	 * 储存招领单
	 * 
	 * @return
	 * @throws Exception
	 */
	public String save() throws Exception {
		try {
			loginInit();
			if (cliamValidate()) {
				applyClaim.setOrderId(orderId);
				applyClaim.setClaimName(claimName);
				applyClaim.setBankName(bankName);
				applyClaim.setClaimAmount(new BigDecimal(claimAmount));
				applyClaim.setExpectDate(DateUtil.convertStringToDate(EcConstant.PATTERN_DATE, expectDate));
				applyClaim.setClaimType(claimType);
				applyClaim.setMemberId(userData.getMemberId());
				applyClaim.setBankTransferId(bktId);
				applyClaim.setClaimStatus("10");// 处理中
				applyClaim.setContactEmail(contactEmail);
				applyClaim.setContactPhone(contactPhone);
				applyClaim.setImgSubName(getUploadFileName().substring(getUploadFileName().lastIndexOf("."),
						getUploadFileName().length()));
				byte[] fileBody = FileCopyUtils.copyToByteArray(getClaimImg());
				applyClaim = transferServiceRemote.saveApplyClaim(applyClaim, fileBody);
				System.out.println("applyClaim.getBankTransferId(){}:" + applyClaim.getBankTransferId());
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return "jsonSaveApplyClaim";
	}

	public String saveSuccess() throws Exception {
		applyClaim = transferService.getApplyClaim(claimId);
		return "success";
	}

	/**
	 * 汇款招领列表
	 * 
	 * @return
	 * @throws Exception
	 */
	public String search() throws Exception {
		return "list";
	}

	public String searchAll() throws Exception {
		String[] sortOrder = { "billDate" };
		CommonCriteria crit = new CommonCriteria();
		// all
		crit.addEq("status", "50");
		bankTransferSize = transferService.getBankTransferListSize(crit).intValue();
		bankTransferList = transferService.getBankTransferList(0, -1, crit, sortOrder);
		return "listAll";
	}

	public String searchBank() throws Exception {
		String[] sortOrder = { "billDate" };
		CommonCriteria crit = new CommonCriteria();
		// bank
		crit.addEq("status", "50");
		crit.addEq("sourceRemit", "BANK");
		bankTransferSize = transferService.getBankTransferListSize(crit).intValue();
		bankTransferList = transferService.getBankTransferList(0, -1, crit, sortOrder);
		return "listBank";
	}

	public String searchPost() throws Exception {
		String[] sortOrder = { "billDate" };
		CommonCriteria crit = new CommonCriteria();
		// post
		crit.addEq("status", "50");
		crit.addEq("sourceRemit", "POST");
		bankTransferSize = transferService.getBankTransferListSize(crit).intValue();
		bankTransferList = transferService.getBankTransferList(0, -1, crit, sortOrder);
		return "listPost";
	}

	public void setApplyClaim(ApplyClaim applyClaim) {
		this.applyClaim = applyClaim;
	}

	public void setBankName(String bankName) {
		this.bankName = bankName;
	}

	public void setBankTransfer(BankTransfer bankTransfer) {
		this.bankTransfer = bankTransfer;
	}

	public void setBankTransferList(List<BankTransfer> bankTransferList) {
		this.bankTransferList = bankTransferList;
	}

	public void setBankTransferSize(int bankTransferSize) {
		this.bankTransferSize = bankTransferSize;
	}

	public void setBktId(String bktId) {
		this.bktId = bktId;
	}

	public void setCheckResult(boolean checkResult) {
		this.checkResult = checkResult;
	}

	public void setClaimAmount(String claimAmount) {
		this.claimAmount = claimAmount;
	}

	public void setClaimId(String claimId) {
		this.claimId = claimId;
	}

	public void setClaimImg(File claimImg) {
		this.claimImg = claimImg;
	}

	public void setClaimName(String claimName) {
		this.claimName = claimName;
	}

	public void setClaimStatusMenu(Menu claimStatusMenu) {
		this.claimStatusMenu = claimStatusMenu;
	}

	public void setClaimType(String claimType) {
		this.claimType = claimType;
	}

	public void setClaimTypeMenu(Menu claimTypeMenu) {
		this.claimTypeMenu = claimTypeMenu;
	}

	public void setContactEmail(String contactEmail) {
		this.contactEmail = contactEmail;
	}

	public void setContactPhone(String contactPhone) {
		this.contactPhone = contactPhone;
	}

	public void setExpectDate(String expectDate) {
		this.expectDate = expectDate;
	}

	public void setMenuService(DomainService<Menu> menuService) {
		this.menuService = menuService;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	public void setPageDescription(String pageDescription) {
		this.pageDescription = pageDescription;
	}

	public void setPageKeywords(String pageKeywords) {
		this.pageKeywords = pageKeywords;
	}

	public void setPager(SimplePager pager) {
		this.pager = pager;
	}

	public void setPageTitle(String pageTitle) {
		this.pageTitle = pageTitle;
	}

	public void setSourceRemitMenu(Menu sourceRemitMenu) {
		this.sourceRemitMenu = sourceRemitMenu;
	}

	public void setTransferService(TransferService transferService) {
		this.transferService = transferService;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public void setUserData(UserData userData) {
		this.userData = userData;
	}

	public void setTransferServiceRemote(TransferService transferServiceRemote) {
		this.transferServiceRemote = transferServiceRemote;
	}
}